<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.1" />
<title>substrateinterface.contracts API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>substrateinterface.contracts</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python"># Python Substrate Interface Library
#
# Copyright 2018-2020 Stichting Polkascan (Polkascan Foundation).
#
# Licensed under the Apache License, Version 2.0 (the &#34;License&#34;);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an &#34;AS IS&#34; BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from packaging import version
from hashlib import blake2b

from substrateinterface.exceptions import ExtrinsicFailedException, DeployContractFailedException, \
    ContractReadFailedException, ContractMetadataParseException
from scalecodec import ScaleBytes, ScaleType, GenericContractExecResult
from substrateinterface.base import SubstrateInterface, Keypair, ExtrinsicReceipt

__all__ = [&#39;ContractExecutionReceipt&#39;, &#39;ContractMetadata&#39;, &#39;ContractCode&#39;, &#39;ContractInstance&#39;, &#39;ContractEvent&#39;]


class ContractMetadata:

    def __init__(self, metadata_dict: dict, substrate: SubstrateInterface):
        &#34;&#34;&#34;
        Class using the generated metadata.json file to represent the metadata of a contract. The metadata_dict is
        parsed and the used types are extracted, composed and added to the type registry of the runtime

        Parameters
        ----------
        metadata_dict
        substrate
        &#34;&#34;&#34;
        self.metadata_dict = metadata_dict
        self.substrate = substrate
        self.type_registry = {}

        self.__type_offset = 0

        self.__parse_type_registry()

    @classmethod
    def create_from_file(cls, metadata_file: str, substrate: SubstrateInterface) -&gt; &#34;ContractMetadata&#34;:
        &#34;&#34;&#34;
        Create a new ContractMetadata object using the provided metadata_file, usually generated by the command
        &#34;cargo +nightly contract generate-metadata&#34; in an ink! project

        Parameters
        ----------
        metadata_file
        substrate

        Returns
        -------
        ContractMetadata
        &#34;&#34;&#34;
        with open(os.path.abspath(metadata_file), &#39;r&#39;) as fp:
            metadata_string = fp.read()
        return cls(json.loads(metadata_string), substrate)

    def __getattr__(self, item):
        if item in self.metadata_dict:
            return self.metadata_dict[item]
        else:
            raise AttributeError(&#34;&#39;{}&#39; object has no attribute &#39;{}&#39;&#34;.format(self.__class__.__name__, item))

    def __parse_type_registry(self):

        # Check requirements
        if &#39;types&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;No &#39;types&#39; directive present in metadata file&#34;)

        if &#39;spec&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;&#39;spec&#39; directive not present in metadata file&#34;)

        if &#39;constructors&#39; not in self.metadata_dict[&#39;spec&#39;]:
            raise ContractMetadataParseException(&#34;No constructors present in metadata file&#34;)

        if &#39;messages&#39; not in self.metadata_dict[&#39;spec&#39;]:
            raise ContractMetadataParseException(&#34;No messages present in metadata file&#34;)

        if &#39;source&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;&#39;source&#39; directive not present in metadata file&#34;)

        # check Metadata version
        if version.parse(self.metadata_dict[&#39;metadataVersion&#39;]) &lt; version.parse(&#39;0.7.0&#39;):
            # Type indexes are 1-based before 0.7.0
            self.__type_offset = 1

        self.type_string_prefix = f&#34;ink.{self.metadata_dict[&#39;source&#39;][&#39;hash&#39;]}&#34;

        for idx, metadata_type in enumerate(self.metadata_dict[&#39;types&#39;]):

            idx += self.__type_offset

            if idx not in self.type_registry:
                self.type_registry[idx] = self.get_type_string_for_metadata_type(idx)

    def generate_constructor_data(self, name, args: dict = None) -&gt; ScaleBytes:
        &#34;&#34;&#34;
        Compose the data field used in the &#34;Contracts.instantiate&#34; call, finding the selectors and encoded the args
        of given constructor

        Parameters
        ----------
        name
        args

        Returns
        -------
        ScaleBytes
        &#34;&#34;&#34;
        if not args:
            args = {}

        for constructor in self.metadata_dict[&#39;spec&#39;][&#39;constructors&#39;]:
            if name in constructor[&#39;name&#39;]:
                data = ScaleBytes(constructor[&#39;selector&#39;])

                for arg in constructor[&#39;args&#39;]:
                    if arg[&#39;name&#39;] not in args:
                        raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                    else:
                        data += self.substrate.encode_scale(
                            type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                            value=args[arg[&#39;name&#39;]]
                        )
                return data

        raise ValueError(f&#39;Constructor &#34;{name}&#34; not found&#39;)

    def get_type_string_for_metadata_type(self, type_id: int) -&gt; str:
        &#34;&#34;&#34;
        Adds a type included in the metadata (represented by an index in the type list) to the type registry and
        produces a type string that can be used in the scope of the `RuntimeConfigurationObject`.

        Parameters
        ----------
        type_id 1-based index of type locating in the metadata types dict

        Returns
        -------
        str
        &#34;&#34;&#34;

        # Check if already processed
        if type_id in self.type_registry:
            return self.type_registry[type_id]

        if type_id &gt; len(self.metadata_dict[&#39;types&#39;]):
            raise ValueError(f&#39;type_id {type_id} not found in metadata&#39;)

        arg_type = self.metadata_dict[&#39;types&#39;][type_id - 1]

        if &#39;path&#39; in arg_type:

            # Option field
            if arg_type[&#39;path&#39;] == [&#39;Option&#39;]:

                # Examine the fields in the &#39;Some&#39; variant
                options_fields = arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;][1][&#39;fields&#39;]

                if len(options_fields) == 1:
                    sub_type = self.get_type_string_for_metadata_type(options_fields[0][&#39;type&#39;])
                else:
                    raise NotImplementedError(&#39;Tuples in Option field not yet supported&#39;)

                return f&#34;Option&lt;{sub_type}&gt;&#34;

            # Predefined types defined in crate ink_env
            if arg_type[&#39;path&#39;][0:2] == [&#39;ink_env&#39;, &#39;types&#39;]:

                if arg_type[&#39;path&#39;][2] == &#39;Timestamp&#39;:
                    return &#39;Moment&#39;

                elif arg_type[&#39;path&#39;][2] in [&#39;AccountId&#39;, &#39;Hash&#39;, &#39;Balance&#39;, &#39;BlockNumber&#39;]:
                    return arg_type[&#39;path&#39;][2]

                else:
                    raise NotImplementedError(f&#34;Unsupported ink_env type &#39;{arg_type[&#39;path&#39;][2]}&#39;&#34;)

        # RUST primitives
        if &#39;primitive&#39; in arg_type[&#39;def&#39;]:
            return arg_type[&#39;def&#39;][&#39;primitive&#39;]

        elif &#39;array&#39; in arg_type[&#39;def&#39;]:
            array_type = self.get_type_string_for_metadata_type(arg_type[&#39;def&#39;][&#39;array&#39;][&#39;type&#39;])
            # Generate unique type string
            return f&#34;[{array_type}; {arg_type[&#39;def&#39;][&#39;array&#39;][&#39;len&#39;]}]&#34;

        elif &#39;variant&#39; in arg_type[&#39;def&#39;]:
            # Create Enum
            type_definition = {
              &#34;type&#34;: &#34;enum&#34;,
              &#34;type_mapping&#34;: []
            }
            for variant in arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;]:

                if &#39;fields&#39; in variant:
                    if len(variant[&#39;fields&#39;]) &gt; 1:
                        raise NotImplementedError(&#39;Tuples as field of enums not supported&#39;)

                    enum_value = self.get_type_string_for_metadata_type(variant[&#39;fields&#39;][0][&#39;type&#39;])

                else:
                    enum_value = &#39;Null&#39;

                type_definition[&#39;type_mapping&#39;].append(
                    [variant[&#39;name&#39;], enum_value]
                )

            # Add to type registry
            self.substrate.runtime_config.update_type_registry_types(
                {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
            )
            # Generate unique type string
            self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

            return f&#39;{self.type_string_prefix}.{type_id}&#39;

        elif &#39;composite&#39; in arg_type[&#39;def&#39;]:
            # Create Struct
            type_definition = {
                &#34;type&#34;: &#34;struct&#34;,
                &#34;type_mapping&#34;: []
            }

            for field in arg_type[&#39;def&#39;][&#39;composite&#39;][&#39;fields&#39;]:
                type_definition[&#39;type_mapping&#39;].append(
                    [field[&#39;name&#39;], self.get_type_string_for_metadata_type(field[&#39;type&#39;])]
                )

            # Add to type registry
            self.substrate.runtime_config.update_type_registry_types(
                {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
            )

            # Generate unique type string
            self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

            return f&#39;{self.type_string_prefix}.{type_id}&#39;
        elif &#39;tuple&#39; in arg_type[&#39;def&#39;]:
            # Create tuple
            elements = [self.get_type_string_for_metadata_type(element) for element in arg_type[&#39;def&#39;][&#39;tuple&#39;]]
            return f&#34;({&#39;,&#39;.join(elements)})&#34;

        raise NotImplementedError(f&#34;Type &#39;{arg_type}&#39; not supported&#34;)

    def get_return_type_string_for_message(self, name) -&gt; str:
        for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
            if name in message[&#39;name&#39;]:
                if message[&#39;returnType&#39;] is None:
                    return &#39;Null&#39;
                else:
                    return self.get_type_string_for_metadata_type(message[&#39;returnType&#39;][&#39;type&#39;])

        raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)

    def generate_message_data(self, name, args: dict = None) -&gt; ScaleBytes:
        &#34;&#34;&#34;
        Compose the data field used in the &#34;Contracts.call&#34; call, finding the selector and encoded the args
        of provided message name

        Parameters
        ----------
        name: name of message in contract
        args: arguments required by message, in format: `{&#39;name&#39;: value}`

        Returns
        -------
        ScaleBytes
        &#34;&#34;&#34;
        if not args:
            args = {}

        for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
            if name in message[&#39;name&#39;]:
                data = ScaleBytes(message[&#39;selector&#39;])

                for arg in message[&#39;args&#39;]:
                    if arg[&#39;name&#39;] not in args:
                        raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                    else:

                        data += self.substrate.encode_scale(
                            type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                            value=args[arg[&#39;name&#39;]]
                        )
                return data

        raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)

    def get_event_data(self, event_id: int) -&gt; dict:
        &#34;&#34;&#34;
        Looks up the event data for given 0-based event_id

        Parameters
        ----------
        event_id

        Returns
        -------

        &#34;&#34;&#34;
        if event_id &gt; len(self.metadata_dict[&#39;spec&#39;][&#39;events&#39;]):
            raise ValueError(f&#39;Event ID {event_id} not found&#39;)

        return self.metadata_dict[&#39;spec&#39;][&#39;events&#39;][event_id]


class ContractEvent(ScaleType):

    def __init__(self, *args, contract_metadata: ContractMetadata = None, **kwargs):
        &#34;&#34;&#34;
        ScaleType class containing information about a specific Contract Event, it decodes the &#34;data&#34; field in
        the generic &#34;Contracts.ContractExecution&#34; event that is triggered after a successfull &#34;Contracts.call&#34; call.
        &#34;&#34;&#34;

        self.contract_metadata = contract_metadata
        self.event_id = None
        self.name = None
        self.docs = None
        self.args = []
        super().__init__(*args, **kwargs)

    def process(self):
        self.event_id = self.process_type(&#39;u8&#39;).value

        event_data = self.contract_metadata.get_event_data(self.event_id)

        self.name = event_data[&#39;name&#39;]
        self.docs = event_data[&#39;docs&#39;]
        self.args = event_data[&#39;args&#39;]

        for arg in self.args:
            # Decode value of event arg with type_string registered in contract
            arg_type_string = self.contract_metadata.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;])
            arg[&#39;value&#39;] = self.process_type(arg_type_string).value

        return {
            &#39;name&#39;: self.name,
            &#39;docs&#39;: self.docs,
            &#39;args&#39;: self.args
        }

    def process_encode(self, value):
        raise NotImplementedError()


class ContractExecutionReceipt(ExtrinsicReceipt):

    def __init__(self, *args, **kwargs):
        &#34;&#34;&#34;
        Object extending the `ExtrinsicReceipt` containing more information about the result after submitting a
        &#34;Contracts.call&#34; extrinsic.

        Parameters
        ----------
        args
        kwargs
        &#34;&#34;&#34;
        self.__contract_events = None
        self.contract_metadata = kwargs.pop(&#39;contract_metadata&#39;)
        super(ContractExecutionReceipt, self).__init__(*args, **kwargs)

    @classmethod
    def create_from_extrinsic_receipt(cls, receipt: ExtrinsicReceipt,
                                      contract_metadata: ContractMetadata) -&gt; &#34;ContractExecutionReceipt&#34;:
        &#34;&#34;&#34;
        Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to
        decode &#34;ContractExecution&#34; events

        Parameters
        ----------
        receipt
        contract_metadata

        Returns
        -------
        ContractExecutionReceipt
        &#34;&#34;&#34;
        return cls(
            substrate=receipt.substrate,
            extrinsic_hash=receipt.extrinsic_hash,
            block_hash=receipt.block_hash,
            finalized=receipt.finalized,
            contract_metadata=contract_metadata
        )

    def process_events(self):
        super().process_events()

        if self.triggered_events:

            self.__contract_events = []

            for event in self.triggered_events:
                if event.event_module.name == &#39;Contracts&#39; and event.event.name == &#39;ContractEmitted&#39;:

                    # Create contract event
                    contract_event_obj = ContractEvent(
                        data=ScaleBytes(event.params[1][&#39;value&#39;]),
                        runtime_config=self.substrate.runtime_config,
                        contract_metadata=self.contract_metadata
                    )

                    contract_event_obj.decode()

                    self.__contract_events.append(contract_event_obj)

    @property
    def contract_events(self):
        if self.__contract_events is None:
            self.process_events()

        return self.__contract_events


class ContractCode:

    def __init__(self, code_hash: bytes = None, metadata: ContractMetadata = None, wasm_bytes: bytes = None,
                 substrate: SubstrateInterface = None):
        &#34;&#34;&#34;
        Object representing the blueprint of the contract, combining either the code hash and metadata of a contract, or
        the WASM bytes and metadata

        Parameters
        ----------
        code_hash: code hash of an already uploaded contract WASM binary
        metadata
        wasm_bytes: WASM binary
        substrate
        &#34;&#34;&#34;
        self.code_hash = code_hash
        self.metadata = metadata
        self.wasm_bytes = wasm_bytes
        self.substrate = substrate

    @classmethod
    def create_from_contract_files(cls, wasm_file: str, metadata_file: str,
                                   substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
        &#34;&#34;&#34;
        Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the
        ink! project

        Parameters
        ----------
        wasm_file
        metadata_file
        substrate

        Returns
        -------
        ContractCode
        &#34;&#34;&#34;

        with open(os.path.abspath(wasm_file), &#39;rb&#39;) as fp:
            wasm_bytes = fp.read()
            code_hash = blake2b(wasm_bytes, digest_size=32).digest()

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(code_hash=code_hash, metadata=metadata, wasm_bytes=wasm_bytes, substrate=substrate)

    @classmethod
    def create_from_code_hash(cls, code_hash: bytes, metadata_file: str,
                              substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
        &#34;&#34;&#34;
        Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file

        Parameters
        ----------
        code_hash
        metadata_file
        substrate

        Returns
        -------
        ContractCode
        &#34;&#34;&#34;

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(code_hash=code_hash, metadata=metadata, substrate=substrate)

    def upload_wasm(self, keypair: Keypair) -&gt; ExtrinsicReceipt:
        &#34;&#34;&#34;
        Created and submits an &#34;Contracts.put_code&#34; extrinsic containing the WASM binary

        Parameters
        ----------
        keypair

        Returns
        -------
        ExtrinsicReceipt
        &#34;&#34;&#34;
        if not self.wasm_bytes:
            raise ValueError(&#34;No WASM bytes to upload&#34;)

        call = self.substrate.compose_call(
            call_module=&#39;Contracts&#39;,
            call_function=&#39;put_code&#39;,
            call_params={
                &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex())
            }
        )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        return self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

    def deploy(self, keypair, endowment, gas_limit, constructor, args: dict = None,
               deployment_salt: str = None, upload_code: bool = False) -&gt; &#34;ContractInstance&#34;:
        &#34;&#34;&#34;
        Deploys a new instance of the contract after its been uploaded on-chain, with provided constructor and
        constructor arguments

        Parameters
        ----------
        keypair
        endowment: Initial deposit for the newly created contract address
        gas_limit:
        constructor: name of the constructor to use, provided in the metadata
        args: arguments for the constructor
        deployment_salt: optional string or hex-string that acts as a salt for this deployment
        upload_code: When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain

        Returns
        -------
        ContractInstance
        &#34;&#34;&#34;

        # Lookup constructor
        data = self.metadata.generate_constructor_data(name=constructor, args=args)

        if upload_code is True:

            # Check metadata for available call functions
            if self.substrate.get_metadata_call_function(&#39;Contracts&#39;, &#39;instantiate_with_code&#39;) is not None:

                if not self.wasm_bytes:
                    raise ValueError(&#34;No WASM bytes to upload&#34;)

                call = self.substrate.compose_call(
                    call_module=&#39;Contracts&#39;,
                    call_function=&#39;instantiate_with_code&#39;,
                    call_params={
                        &#39;endowment&#39;: endowment,
                        &#39;gas_limit&#39;: gas_limit,
                        &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex()),
                        &#39;data&#39;: data.to_hex(),
                        &#39;salt&#39;: deployment_salt or &#39;&#39;
                    }
                )
            else:
                # Legacy mode: put code in seperate call

                self.upload_wasm(keypair)

                call = self.substrate.compose_call(
                    call_module=&#39;Contracts&#39;,
                    call_function=&#39;instantiate&#39;,
                    call_params={
                        &#39;endowment&#39;: endowment,
                        &#39;gas_limit&#39;: gas_limit,
                        &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                        &#39;data&#39;: data.to_hex(),
                        &#39;salt&#39;: deployment_salt or &#39;&#39;
                    }
                )
        else:

            call = self.substrate.compose_call(
                call_module=&#39;Contracts&#39;,
                call_function=&#39;instantiate&#39;,
                call_params={
                    &#39;endowment&#39;: endowment,
                    &#39;gas_limit&#39;: gas_limit,
                    &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                    &#39;data&#39;: data.to_hex(),
                    &#39;salt&#39;: deployment_salt or &#39;&#39;
                }
            )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        result = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

        if not result.is_success:
            raise ExtrinsicFailedException(result.error_message)

        for event in result.triggered_events:
            if event.event.name == &#39;Instantiated&#39;:
                return ContractInstance(
                    contract_address=event.params[1][&#39;value&#39;],
                    metadata=self.metadata,
                    substrate=self.substrate
                )

        raise DeployContractFailedException()


class ContractInstance:

    def __init__(self, contract_address: str, metadata: ContractMetadata = None, substrate: SubstrateInterface = None):
        self.substrate = substrate
        self.contract_address = contract_address
        self.metadata = metadata

    @classmethod
    def create_from_address(cls, contract_address: str, metadata_file: str,
                            substrate: SubstrateInterface = None) -&gt; &#34;ContractInstance&#34;:
        &#34;&#34;&#34;
        Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the
        metadata JSON of that contract

        Parameters
        ----------
        contract_address: SS58-address of contract
        metadata_file: path to metadata JSON generated for contract
        substrate

        Returns
        -------
        ContractInstance
        &#34;&#34;&#34;

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(contract_address=contract_address, metadata=metadata, substrate=substrate)

    def read(self, keypair: Keypair, method: str, args: dict = None,
             value: int = 0, gas_limit: int = 5000000000000) -&gt; GenericContractExecResult:
        &#34;&#34;&#34;
        Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used
        to predict gas limits and &#39;dry-run&#39; the execution when a mutable message is used.
        This method does not submit an extrinsic.

        Parameters
        ----------
        keypair
        method: name of message to execute
        args: arguments of message in {&#39;name&#39;: value} format
        value: value to send when executing the message
        gas_limit:

        Returns
        -------
        GenericContractExecResult
        &#34;&#34;&#34;

        input_data = self.metadata.generate_message_data(name=method, args=args)

        response = self.substrate.rpc_request(method=&#39;contracts_call&#39;, params=[{
            &#39;dest&#39;: self.contract_address,
            &#39;gasLimit&#39;: gas_limit,
            &#39;inputData&#39;: input_data.to_hex(),
            &#39;origin&#39;: keypair.ss58_address,
            &#39;value&#39;: value
        }])

        if &#39;result&#39; in response:

            return_type_string = self.metadata.get_return_type_string_for_message(method)

            # Wrap the result in a ContractExecResult Enum because the exec will result in the same
            ContractExecResult = self.substrate.runtime_config.get_decoder_class(&#39;ContractExecResult&#39;)

            contract_exec_result = ContractExecResult(contract_result_scale_type=return_type_string)

            if &#39;result&#39; in response[&#39;result&#39;]:

                contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;gasConsumed&#39;]

                if &#39;Ok&#39; in response[&#39;result&#39;][&#39;result&#39;]:

                    contract_exec_result.flags = response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;flags&#39;]

                    try:

                        result_scale_obj = self.substrate.decode_scale(
                            type_string=return_type_string,
                            scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;]),
                            return_scale_obj=True
                        )

                        response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;] = result_scale_obj.value
                        contract_exec_result.contract_result_data = result_scale_obj

                    except NotImplementedError:
                        pass

            # Backwards compatibility
            elif &#39;success&#39; in response[&#39;result&#39;]:

                contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;success&#39;][&#39;gas_consumed&#39;]
                contract_exec_result.flags = response[&#39;result&#39;][&#39;success&#39;][&#39;flags&#39;]

                try:

                    result_scale_obj = self.substrate.decode_scale(
                        type_string=return_type_string,
                        scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;]),
                        return_scale_obj=True
                    )

                    response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;] = result_scale_obj.value
                    contract_exec_result.contract_result_data = result_scale_obj

                except NotImplementedError:
                    pass

            contract_exec_result.value = response[&#39;result&#39;]

            return contract_exec_result

        raise ContractReadFailedException(response)

    def exec(self, keypair: Keypair, method: str, args: dict = None,
             value: int = 0, gas_limit: int = 200000) -&gt; ContractExecutionReceipt:
        &#34;&#34;&#34;
        Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a
        &#39;dry-run&#39; of executing this message, see `ContractInstance.read`.

        Parameters
        ----------
        keypair
        method: name of message to execute
        args: arguments of message in {&#39;name&#39;: value} format
        value: value to send when executing the message
        gas_limit

        Returns
        -------
        ContractExecutionReceipt
        &#34;&#34;&#34;

        input_data = self.metadata.generate_message_data(name=method, args=args)

        call = self.substrate.compose_call(
            call_module=&#39;Contracts&#39;,
            call_function=&#39;call&#39;,
            call_params={
                &#39;dest&#39;: self.contract_address,
                &#39;value&#39;: value,
                &#39;gas_limit&#39;: gas_limit,
                &#39;data&#39;: input_data.to_hex()
            }
        )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        receipt = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

        return ContractExecutionReceipt.create_from_extrinsic_receipt(receipt, self.metadata)</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="substrateinterface.contracts.ContractCode"><code class="flex name class">
<span>class <span class="ident">ContractCode</span></span>
<span>(</span><span>code_hash: bytes = None, metadata: <a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a> = None, wasm_bytes: bytes = None, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a> = None)</span>
</code></dt>
<dd>
<div class="desc"><p>Object representing the blueprint of the contract, combining either the code hash and metadata of a contract, or
the WASM bytes and metadata</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>code_hash</code></strong> :&ensp;<code>code hash</code> of <code>an already uploaded contract WASM binary</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>metadata</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>wasm_bytes</code></strong> :&ensp;<code>WASM binary</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContractCode:

    def __init__(self, code_hash: bytes = None, metadata: ContractMetadata = None, wasm_bytes: bytes = None,
                 substrate: SubstrateInterface = None):
        &#34;&#34;&#34;
        Object representing the blueprint of the contract, combining either the code hash and metadata of a contract, or
        the WASM bytes and metadata

        Parameters
        ----------
        code_hash: code hash of an already uploaded contract WASM binary
        metadata
        wasm_bytes: WASM binary
        substrate
        &#34;&#34;&#34;
        self.code_hash = code_hash
        self.metadata = metadata
        self.wasm_bytes = wasm_bytes
        self.substrate = substrate

    @classmethod
    def create_from_contract_files(cls, wasm_file: str, metadata_file: str,
                                   substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
        &#34;&#34;&#34;
        Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the
        ink! project

        Parameters
        ----------
        wasm_file
        metadata_file
        substrate

        Returns
        -------
        ContractCode
        &#34;&#34;&#34;

        with open(os.path.abspath(wasm_file), &#39;rb&#39;) as fp:
            wasm_bytes = fp.read()
            code_hash = blake2b(wasm_bytes, digest_size=32).digest()

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(code_hash=code_hash, metadata=metadata, wasm_bytes=wasm_bytes, substrate=substrate)

    @classmethod
    def create_from_code_hash(cls, code_hash: bytes, metadata_file: str,
                              substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
        &#34;&#34;&#34;
        Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file

        Parameters
        ----------
        code_hash
        metadata_file
        substrate

        Returns
        -------
        ContractCode
        &#34;&#34;&#34;

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(code_hash=code_hash, metadata=metadata, substrate=substrate)

    def upload_wasm(self, keypair: Keypair) -&gt; ExtrinsicReceipt:
        &#34;&#34;&#34;
        Created and submits an &#34;Contracts.put_code&#34; extrinsic containing the WASM binary

        Parameters
        ----------
        keypair

        Returns
        -------
        ExtrinsicReceipt
        &#34;&#34;&#34;
        if not self.wasm_bytes:
            raise ValueError(&#34;No WASM bytes to upload&#34;)

        call = self.substrate.compose_call(
            call_module=&#39;Contracts&#39;,
            call_function=&#39;put_code&#39;,
            call_params={
                &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex())
            }
        )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        return self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

    def deploy(self, keypair, endowment, gas_limit, constructor, args: dict = None,
               deployment_salt: str = None, upload_code: bool = False) -&gt; &#34;ContractInstance&#34;:
        &#34;&#34;&#34;
        Deploys a new instance of the contract after its been uploaded on-chain, with provided constructor and
        constructor arguments

        Parameters
        ----------
        keypair
        endowment: Initial deposit for the newly created contract address
        gas_limit:
        constructor: name of the constructor to use, provided in the metadata
        args: arguments for the constructor
        deployment_salt: optional string or hex-string that acts as a salt for this deployment
        upload_code: When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain

        Returns
        -------
        ContractInstance
        &#34;&#34;&#34;

        # Lookup constructor
        data = self.metadata.generate_constructor_data(name=constructor, args=args)

        if upload_code is True:

            # Check metadata for available call functions
            if self.substrate.get_metadata_call_function(&#39;Contracts&#39;, &#39;instantiate_with_code&#39;) is not None:

                if not self.wasm_bytes:
                    raise ValueError(&#34;No WASM bytes to upload&#34;)

                call = self.substrate.compose_call(
                    call_module=&#39;Contracts&#39;,
                    call_function=&#39;instantiate_with_code&#39;,
                    call_params={
                        &#39;endowment&#39;: endowment,
                        &#39;gas_limit&#39;: gas_limit,
                        &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex()),
                        &#39;data&#39;: data.to_hex(),
                        &#39;salt&#39;: deployment_salt or &#39;&#39;
                    }
                )
            else:
                # Legacy mode: put code in seperate call

                self.upload_wasm(keypair)

                call = self.substrate.compose_call(
                    call_module=&#39;Contracts&#39;,
                    call_function=&#39;instantiate&#39;,
                    call_params={
                        &#39;endowment&#39;: endowment,
                        &#39;gas_limit&#39;: gas_limit,
                        &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                        &#39;data&#39;: data.to_hex(),
                        &#39;salt&#39;: deployment_salt or &#39;&#39;
                    }
                )
        else:

            call = self.substrate.compose_call(
                call_module=&#39;Contracts&#39;,
                call_function=&#39;instantiate&#39;,
                call_params={
                    &#39;endowment&#39;: endowment,
                    &#39;gas_limit&#39;: gas_limit,
                    &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                    &#39;data&#39;: data.to_hex(),
                    &#39;salt&#39;: deployment_salt or &#39;&#39;
                }
            )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        result = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

        if not result.is_success:
            raise ExtrinsicFailedException(result.error_message)

        for event in result.triggered_events:
            if event.event.name == &#39;Instantiated&#39;:
                return ContractInstance(
                    contract_address=event.params[1][&#39;value&#39;],
                    metadata=self.metadata,
                    substrate=self.substrate
                )

        raise DeployContractFailedException()</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractCode.create_from_code_hash"><code class="name flex">
<span>def <span class="ident">create_from_code_hash</span></span>(<span>code_hash: bytes, metadata_file: str, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a>) ‑> <a title="substrateinterface.contracts.ContractCode" href="#substrateinterface.contracts.ContractCode">ContractCode</a></span>
</code></dt>
<dd>
<div class="desc"><p>Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>code_hash</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>metadata_file</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractCode" href="#substrateinterface.contracts.ContractCode">ContractCode</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@classmethod
def create_from_code_hash(cls, code_hash: bytes, metadata_file: str,
                          substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
    &#34;&#34;&#34;
    Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file

    Parameters
    ----------
    code_hash
    metadata_file
    substrate

    Returns
    -------
    ContractCode
    &#34;&#34;&#34;

    metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

    return cls(code_hash=code_hash, metadata=metadata, substrate=substrate)</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractCode.create_from_contract_files"><code class="name flex">
<span>def <span class="ident">create_from_contract_files</span></span>(<span>wasm_file: str, metadata_file: str, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a>) ‑> <a title="substrateinterface.contracts.ContractCode" href="#substrateinterface.contracts.ContractCode">ContractCode</a></span>
</code></dt>
<dd>
<div class="desc"><p>Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the
ink! project</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>wasm_file</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>metadata_file</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractCode" href="#substrateinterface.contracts.ContractCode">ContractCode</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@classmethod
def create_from_contract_files(cls, wasm_file: str, metadata_file: str,
                               substrate: SubstrateInterface) -&gt; &#34;ContractCode&#34;:
    &#34;&#34;&#34;
    Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the
    ink! project

    Parameters
    ----------
    wasm_file
    metadata_file
    substrate

    Returns
    -------
    ContractCode
    &#34;&#34;&#34;

    with open(os.path.abspath(wasm_file), &#39;rb&#39;) as fp:
        wasm_bytes = fp.read()
        code_hash = blake2b(wasm_bytes, digest_size=32).digest()

    metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

    return cls(code_hash=code_hash, metadata=metadata, wasm_bytes=wasm_bytes, substrate=substrate)</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractCode.deploy"><code class="name flex">
<span>def <span class="ident">deploy</span></span>(<span>self, keypair, endowment, gas_limit, constructor, args: dict = None, deployment_salt: str = None, upload_code: bool = False) ‑> <a title="substrateinterface.contracts.ContractInstance" href="#substrateinterface.contracts.ContractInstance">ContractInstance</a></span>
</code></dt>
<dd>
<div class="desc"><p>Deploys a new instance of the contract after its been uploaded on-chain, with provided constructor and
constructor arguments</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>keypair</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>endowment</code></strong> :&ensp;<code>Initial deposit for the newly created contract address</code></dt>
<dd>&nbsp;</dd>
<dt>gas_limit:</dt>
<dt><strong><code>constructor</code></strong> :&ensp;<code>name</code> of <code>the constructor to use, provided in the metadata</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>args</code></strong> :&ensp;<code>arguments for the constructor</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>deployment_salt</code></strong> :&ensp;<code>optional string</code> or <code>hex-string that acts as a salt for this deployment</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>upload_code</code></strong> :&ensp;<code>When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain</code></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractInstance" href="#substrateinterface.contracts.ContractInstance">ContractInstance</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def deploy(self, keypair, endowment, gas_limit, constructor, args: dict = None,
           deployment_salt: str = None, upload_code: bool = False) -&gt; &#34;ContractInstance&#34;:
    &#34;&#34;&#34;
    Deploys a new instance of the contract after its been uploaded on-chain, with provided constructor and
    constructor arguments

    Parameters
    ----------
    keypair
    endowment: Initial deposit for the newly created contract address
    gas_limit:
    constructor: name of the constructor to use, provided in the metadata
    args: arguments for the constructor
    deployment_salt: optional string or hex-string that acts as a salt for this deployment
    upload_code: When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain

    Returns
    -------
    ContractInstance
    &#34;&#34;&#34;

    # Lookup constructor
    data = self.metadata.generate_constructor_data(name=constructor, args=args)

    if upload_code is True:

        # Check metadata for available call functions
        if self.substrate.get_metadata_call_function(&#39;Contracts&#39;, &#39;instantiate_with_code&#39;) is not None:

            if not self.wasm_bytes:
                raise ValueError(&#34;No WASM bytes to upload&#34;)

            call = self.substrate.compose_call(
                call_module=&#39;Contracts&#39;,
                call_function=&#39;instantiate_with_code&#39;,
                call_params={
                    &#39;endowment&#39;: endowment,
                    &#39;gas_limit&#39;: gas_limit,
                    &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex()),
                    &#39;data&#39;: data.to_hex(),
                    &#39;salt&#39;: deployment_salt or &#39;&#39;
                }
            )
        else:
            # Legacy mode: put code in seperate call

            self.upload_wasm(keypair)

            call = self.substrate.compose_call(
                call_module=&#39;Contracts&#39;,
                call_function=&#39;instantiate&#39;,
                call_params={
                    &#39;endowment&#39;: endowment,
                    &#39;gas_limit&#39;: gas_limit,
                    &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                    &#39;data&#39;: data.to_hex(),
                    &#39;salt&#39;: deployment_salt or &#39;&#39;
                }
            )
    else:

        call = self.substrate.compose_call(
            call_module=&#39;Contracts&#39;,
            call_function=&#39;instantiate&#39;,
            call_params={
                &#39;endowment&#39;: endowment,
                &#39;gas_limit&#39;: gas_limit,
                &#39;code_hash&#39;: f&#39;0x{self.code_hash.hex()}&#39;,
                &#39;data&#39;: data.to_hex(),
                &#39;salt&#39;: deployment_salt or &#39;&#39;
            }
        )

    extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

    result = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

    if not result.is_success:
        raise ExtrinsicFailedException(result.error_message)

    for event in result.triggered_events:
        if event.event.name == &#39;Instantiated&#39;:
            return ContractInstance(
                contract_address=event.params[1][&#39;value&#39;],
                metadata=self.metadata,
                substrate=self.substrate
            )

    raise DeployContractFailedException()</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractCode.upload_wasm"><code class="name flex">
<span>def <span class="ident">upload_wasm</span></span>(<span>self, keypair: <a title="substrateinterface.base.Keypair" href="base.html#substrateinterface.base.Keypair">Keypair</a>) ‑> <a title="substrateinterface.base.ExtrinsicReceipt" href="base.html#substrateinterface.base.ExtrinsicReceipt">ExtrinsicReceipt</a></span>
</code></dt>
<dd>
<div class="desc"><p>Created and submits an "Contracts.put_code" extrinsic containing the WASM binary</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>keypair</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ExtrinsicReceipt</code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def upload_wasm(self, keypair: Keypair) -&gt; ExtrinsicReceipt:
    &#34;&#34;&#34;
    Created and submits an &#34;Contracts.put_code&#34; extrinsic containing the WASM binary

    Parameters
    ----------
    keypair

    Returns
    -------
    ExtrinsicReceipt
    &#34;&#34;&#34;
    if not self.wasm_bytes:
        raise ValueError(&#34;No WASM bytes to upload&#34;)

    call = self.substrate.compose_call(
        call_module=&#39;Contracts&#39;,
        call_function=&#39;put_code&#39;,
        call_params={
            &#39;code&#39;: &#39;0x{}&#39;.format(self.wasm_bytes.hex())
        }
    )

    extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

    return self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="substrateinterface.contracts.ContractEvent"><code class="flex name class">
<span>class <span class="ident">ContractEvent</span></span>
<span>(</span><span>*args, contract_metadata: <a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a> = None, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>Helper class that provides a standard way to create an ABC using
inheritance.</p>
<p>ScaleType class containing information about a specific Contract Event, it decodes the "data" field in
the generic "Contracts.ContractExecution" event that is triggered after a successfull "Contracts.call" call.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContractEvent(ScaleType):

    def __init__(self, *args, contract_metadata: ContractMetadata = None, **kwargs):
        &#34;&#34;&#34;
        ScaleType class containing information about a specific Contract Event, it decodes the &#34;data&#34; field in
        the generic &#34;Contracts.ContractExecution&#34; event that is triggered after a successfull &#34;Contracts.call&#34; call.
        &#34;&#34;&#34;

        self.contract_metadata = contract_metadata
        self.event_id = None
        self.name = None
        self.docs = None
        self.args = []
        super().__init__(*args, **kwargs)

    def process(self):
        self.event_id = self.process_type(&#39;u8&#39;).value

        event_data = self.contract_metadata.get_event_data(self.event_id)

        self.name = event_data[&#39;name&#39;]
        self.docs = event_data[&#39;docs&#39;]
        self.args = event_data[&#39;args&#39;]

        for arg in self.args:
            # Decode value of event arg with type_string registered in contract
            arg_type_string = self.contract_metadata.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;])
            arg[&#39;value&#39;] = self.process_type(arg_type_string).value

        return {
            &#39;name&#39;: self.name,
            &#39;docs&#39;: self.docs,
            &#39;args&#39;: self.args
        }

    def process_encode(self, value):
        raise NotImplementedError()</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>scalecodec.base.ScaleType</li>
<li>scalecodec.base.ScaleDecoder</li>
<li>abc.ABC</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractEvent.process"><code class="name flex">
<span>def <span class="ident">process</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def process(self):
    self.event_id = self.process_type(&#39;u8&#39;).value

    event_data = self.contract_metadata.get_event_data(self.event_id)

    self.name = event_data[&#39;name&#39;]
    self.docs = event_data[&#39;docs&#39;]
    self.args = event_data[&#39;args&#39;]

    for arg in self.args:
        # Decode value of event arg with type_string registered in contract
        arg_type_string = self.contract_metadata.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;])
        arg[&#39;value&#39;] = self.process_type(arg_type_string).value

    return {
        &#39;name&#39;: self.name,
        &#39;docs&#39;: self.docs,
        &#39;args&#39;: self.args
    }</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractEvent.process_encode"><code class="name flex">
<span>def <span class="ident">process_encode</span></span>(<span>self, value)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def process_encode(self, value):
    raise NotImplementedError()</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="substrateinterface.contracts.ContractExecutionReceipt"><code class="flex name class">
<span>class <span class="ident">ContractExecutionReceipt</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>Object extending the <code>ExtrinsicReceipt</code> containing more information about the result after submitting a
"Contracts.call" extrinsic.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>args</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>kwargs</code></strong></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContractExecutionReceipt(ExtrinsicReceipt):

    def __init__(self, *args, **kwargs):
        &#34;&#34;&#34;
        Object extending the `ExtrinsicReceipt` containing more information about the result after submitting a
        &#34;Contracts.call&#34; extrinsic.

        Parameters
        ----------
        args
        kwargs
        &#34;&#34;&#34;
        self.__contract_events = None
        self.contract_metadata = kwargs.pop(&#39;contract_metadata&#39;)
        super(ContractExecutionReceipt, self).__init__(*args, **kwargs)

    @classmethod
    def create_from_extrinsic_receipt(cls, receipt: ExtrinsicReceipt,
                                      contract_metadata: ContractMetadata) -&gt; &#34;ContractExecutionReceipt&#34;:
        &#34;&#34;&#34;
        Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to
        decode &#34;ContractExecution&#34; events

        Parameters
        ----------
        receipt
        contract_metadata

        Returns
        -------
        ContractExecutionReceipt
        &#34;&#34;&#34;
        return cls(
            substrate=receipt.substrate,
            extrinsic_hash=receipt.extrinsic_hash,
            block_hash=receipt.block_hash,
            finalized=receipt.finalized,
            contract_metadata=contract_metadata
        )

    def process_events(self):
        super().process_events()

        if self.triggered_events:

            self.__contract_events = []

            for event in self.triggered_events:
                if event.event_module.name == &#39;Contracts&#39; and event.event.name == &#39;ContractEmitted&#39;:

                    # Create contract event
                    contract_event_obj = ContractEvent(
                        data=ScaleBytes(event.params[1][&#39;value&#39;]),
                        runtime_config=self.substrate.runtime_config,
                        contract_metadata=self.contract_metadata
                    )

                    contract_event_obj.decode()

                    self.__contract_events.append(contract_event_obj)

    @property
    def contract_events(self):
        if self.__contract_events is None:
            self.process_events()

        return self.__contract_events</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="substrateinterface.base.ExtrinsicReceipt" href="base.html#substrateinterface.base.ExtrinsicReceipt">ExtrinsicReceipt</a></li>
</ul>
<h3>Static methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractExecutionReceipt.create_from_extrinsic_receipt"><code class="name flex">
<span>def <span class="ident">create_from_extrinsic_receipt</span></span>(<span>receipt: <a title="substrateinterface.base.ExtrinsicReceipt" href="base.html#substrateinterface.base.ExtrinsicReceipt">ExtrinsicReceipt</a>, contract_metadata: <a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a>) ‑> <a title="substrateinterface.contracts.ContractExecutionReceipt" href="#substrateinterface.contracts.ContractExecutionReceipt">ContractExecutionReceipt</a></span>
</code></dt>
<dd>
<div class="desc"><p>Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to
decode "ContractExecution" events</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>receipt</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>contract_metadata</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractExecutionReceipt" href="#substrateinterface.contracts.ContractExecutionReceipt">ContractExecutionReceipt</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@classmethod
def create_from_extrinsic_receipt(cls, receipt: ExtrinsicReceipt,
                                  contract_metadata: ContractMetadata) -&gt; &#34;ContractExecutionReceipt&#34;:
    &#34;&#34;&#34;
    Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to
    decode &#34;ContractExecution&#34; events

    Parameters
    ----------
    receipt
    contract_metadata

    Returns
    -------
    ContractExecutionReceipt
    &#34;&#34;&#34;
    return cls(
        substrate=receipt.substrate,
        extrinsic_hash=receipt.extrinsic_hash,
        block_hash=receipt.block_hash,
        finalized=receipt.finalized,
        contract_metadata=contract_metadata
    )</code></pre>
</details>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="substrateinterface.contracts.ContractExecutionReceipt.contract_events"><code class="name">var <span class="ident">contract_events</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def contract_events(self):
    if self.__contract_events is None:
        self.process_events()

    return self.__contract_events</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractExecutionReceipt.process_events"><code class="name flex">
<span>def <span class="ident">process_events</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def process_events(self):
    super().process_events()

    if self.triggered_events:

        self.__contract_events = []

        for event in self.triggered_events:
            if event.event_module.name == &#39;Contracts&#39; and event.event.name == &#39;ContractEmitted&#39;:

                # Create contract event
                contract_event_obj = ContractEvent(
                    data=ScaleBytes(event.params[1][&#39;value&#39;]),
                    runtime_config=self.substrate.runtime_config,
                    contract_metadata=self.contract_metadata
                )

                contract_event_obj.decode()

                self.__contract_events.append(contract_event_obj)</code></pre>
</details>
</dd>
</dl>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="substrateinterface.base.ExtrinsicReceipt" href="base.html#substrateinterface.base.ExtrinsicReceipt">ExtrinsicReceipt</a></b></code>:
<ul class="hlist">
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.error_message" href="base.html#substrateinterface.base.ExtrinsicReceipt.error_message">error_message</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.extrinsic" href="base.html#substrateinterface.base.ExtrinsicReceipt.extrinsic">extrinsic</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.extrinsic_idx" href="base.html#substrateinterface.base.ExtrinsicReceipt.extrinsic_idx">extrinsic_idx</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.is_success" href="base.html#substrateinterface.base.ExtrinsicReceipt.is_success">is_success</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.total_fee_amount" href="base.html#substrateinterface.base.ExtrinsicReceipt.total_fee_amount">total_fee_amount</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.triggered_events" href="base.html#substrateinterface.base.ExtrinsicReceipt.triggered_events">triggered_events</a></code></li>
<li><code><a title="substrateinterface.base.ExtrinsicReceipt.weight" href="base.html#substrateinterface.base.ExtrinsicReceipt.weight">weight</a></code></li>
</ul>
</li>
</ul>
</dd>
<dt id="substrateinterface.contracts.ContractInstance"><code class="flex name class">
<span>class <span class="ident">ContractInstance</span></span>
<span>(</span><span>contract_address: str, metadata: <a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a> = None, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a> = None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContractInstance:

    def __init__(self, contract_address: str, metadata: ContractMetadata = None, substrate: SubstrateInterface = None):
        self.substrate = substrate
        self.contract_address = contract_address
        self.metadata = metadata

    @classmethod
    def create_from_address(cls, contract_address: str, metadata_file: str,
                            substrate: SubstrateInterface = None) -&gt; &#34;ContractInstance&#34;:
        &#34;&#34;&#34;
        Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the
        metadata JSON of that contract

        Parameters
        ----------
        contract_address: SS58-address of contract
        metadata_file: path to metadata JSON generated for contract
        substrate

        Returns
        -------
        ContractInstance
        &#34;&#34;&#34;

        metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

        return cls(contract_address=contract_address, metadata=metadata, substrate=substrate)

    def read(self, keypair: Keypair, method: str, args: dict = None,
             value: int = 0, gas_limit: int = 5000000000000) -&gt; GenericContractExecResult:
        &#34;&#34;&#34;
        Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used
        to predict gas limits and &#39;dry-run&#39; the execution when a mutable message is used.
        This method does not submit an extrinsic.

        Parameters
        ----------
        keypair
        method: name of message to execute
        args: arguments of message in {&#39;name&#39;: value} format
        value: value to send when executing the message
        gas_limit:

        Returns
        -------
        GenericContractExecResult
        &#34;&#34;&#34;

        input_data = self.metadata.generate_message_data(name=method, args=args)

        response = self.substrate.rpc_request(method=&#39;contracts_call&#39;, params=[{
            &#39;dest&#39;: self.contract_address,
            &#39;gasLimit&#39;: gas_limit,
            &#39;inputData&#39;: input_data.to_hex(),
            &#39;origin&#39;: keypair.ss58_address,
            &#39;value&#39;: value
        }])

        if &#39;result&#39; in response:

            return_type_string = self.metadata.get_return_type_string_for_message(method)

            # Wrap the result in a ContractExecResult Enum because the exec will result in the same
            ContractExecResult = self.substrate.runtime_config.get_decoder_class(&#39;ContractExecResult&#39;)

            contract_exec_result = ContractExecResult(contract_result_scale_type=return_type_string)

            if &#39;result&#39; in response[&#39;result&#39;]:

                contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;gasConsumed&#39;]

                if &#39;Ok&#39; in response[&#39;result&#39;][&#39;result&#39;]:

                    contract_exec_result.flags = response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;flags&#39;]

                    try:

                        result_scale_obj = self.substrate.decode_scale(
                            type_string=return_type_string,
                            scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;]),
                            return_scale_obj=True
                        )

                        response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;] = result_scale_obj.value
                        contract_exec_result.contract_result_data = result_scale_obj

                    except NotImplementedError:
                        pass

            # Backwards compatibility
            elif &#39;success&#39; in response[&#39;result&#39;]:

                contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;success&#39;][&#39;gas_consumed&#39;]
                contract_exec_result.flags = response[&#39;result&#39;][&#39;success&#39;][&#39;flags&#39;]

                try:

                    result_scale_obj = self.substrate.decode_scale(
                        type_string=return_type_string,
                        scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;]),
                        return_scale_obj=True
                    )

                    response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;] = result_scale_obj.value
                    contract_exec_result.contract_result_data = result_scale_obj

                except NotImplementedError:
                    pass

            contract_exec_result.value = response[&#39;result&#39;]

            return contract_exec_result

        raise ContractReadFailedException(response)

    def exec(self, keypair: Keypair, method: str, args: dict = None,
             value: int = 0, gas_limit: int = 200000) -&gt; ContractExecutionReceipt:
        &#34;&#34;&#34;
        Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a
        &#39;dry-run&#39; of executing this message, see `ContractInstance.read`.

        Parameters
        ----------
        keypair
        method: name of message to execute
        args: arguments of message in {&#39;name&#39;: value} format
        value: value to send when executing the message
        gas_limit

        Returns
        -------
        ContractExecutionReceipt
        &#34;&#34;&#34;

        input_data = self.metadata.generate_message_data(name=method, args=args)

        call = self.substrate.compose_call(
            call_module=&#39;Contracts&#39;,
            call_function=&#39;call&#39;,
            call_params={
                &#39;dest&#39;: self.contract_address,
                &#39;value&#39;: value,
                &#39;gas_limit&#39;: gas_limit,
                &#39;data&#39;: input_data.to_hex()
            }
        )

        extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

        receipt = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

        return ContractExecutionReceipt.create_from_extrinsic_receipt(receipt, self.metadata)</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractInstance.create_from_address"><code class="name flex">
<span>def <span class="ident">create_from_address</span></span>(<span>contract_address: str, metadata_file: str, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a> = None) ‑> <a title="substrateinterface.contracts.ContractInstance" href="#substrateinterface.contracts.ContractInstance">ContractInstance</a></span>
</code></dt>
<dd>
<div class="desc"><p>Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the
metadata JSON of that contract</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>contract_address</code></strong> :&ensp;<code>SS58-address</code> of <code>contract</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>metadata_file</code></strong> :&ensp;<code>path to metadata JSON generated for contract</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractInstance" href="#substrateinterface.contracts.ContractInstance">ContractInstance</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@classmethod
def create_from_address(cls, contract_address: str, metadata_file: str,
                        substrate: SubstrateInterface = None) -&gt; &#34;ContractInstance&#34;:
    &#34;&#34;&#34;
    Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the
    metadata JSON of that contract

    Parameters
    ----------
    contract_address: SS58-address of contract
    metadata_file: path to metadata JSON generated for contract
    substrate

    Returns
    -------
    ContractInstance
    &#34;&#34;&#34;

    metadata = ContractMetadata.create_from_file(metadata_file, substrate=substrate)

    return cls(contract_address=contract_address, metadata=metadata, substrate=substrate)</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractInstance.exec"><code class="name flex">
<span>def <span class="ident">exec</span></span>(<span>self, keypair: <a title="substrateinterface.base.Keypair" href="base.html#substrateinterface.base.Keypair">Keypair</a>, method: str, args: dict = None, value: int = 0, gas_limit: int = 200000) ‑> <a title="substrateinterface.contracts.ContractExecutionReceipt" href="#substrateinterface.contracts.ContractExecutionReceipt">ContractExecutionReceipt</a></span>
</code></dt>
<dd>
<div class="desc"><p>Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a
'dry-run' of executing this message, see <code><a title="substrateinterface.contracts.ContractInstance.read" href="#substrateinterface.contracts.ContractInstance.read">ContractInstance.read()</a></code>.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>keypair</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>method</code></strong> :&ensp;<code>name</code> of <code>message to execute</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>args</code></strong> :&ensp;<code>arguments</code> of <code>message in {'name': value} format</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>value</code></strong> :&ensp;<code>value to send when executing the message</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>gas_limit</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractExecutionReceipt" href="#substrateinterface.contracts.ContractExecutionReceipt">ContractExecutionReceipt</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def exec(self, keypair: Keypair, method: str, args: dict = None,
         value: int = 0, gas_limit: int = 200000) -&gt; ContractExecutionReceipt:
    &#34;&#34;&#34;
    Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a
    &#39;dry-run&#39; of executing this message, see `ContractInstance.read`.

    Parameters
    ----------
    keypair
    method: name of message to execute
    args: arguments of message in {&#39;name&#39;: value} format
    value: value to send when executing the message
    gas_limit

    Returns
    -------
    ContractExecutionReceipt
    &#34;&#34;&#34;

    input_data = self.metadata.generate_message_data(name=method, args=args)

    call = self.substrate.compose_call(
        call_module=&#39;Contracts&#39;,
        call_function=&#39;call&#39;,
        call_params={
            &#39;dest&#39;: self.contract_address,
            &#39;value&#39;: value,
            &#39;gas_limit&#39;: gas_limit,
            &#39;data&#39;: input_data.to_hex()
        }
    )

    extrinsic = self.substrate.create_signed_extrinsic(call=call, keypair=keypair)

    receipt = self.substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

    return ContractExecutionReceipt.create_from_extrinsic_receipt(receipt, self.metadata)</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractInstance.read"><code class="name flex">
<span>def <span class="ident">read</span></span>(<span>self, keypair: <a title="substrateinterface.base.Keypair" href="base.html#substrateinterface.base.Keypair">Keypair</a>, method: str, args: dict = None, value: int = 0, gas_limit: int = 5000000000000) ‑> scalecodec.types.GenericContractExecResult</span>
</code></dt>
<dd>
<div class="desc"><p>Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used
to predict gas limits and 'dry-run' the execution when a mutable message is used.
This method does not submit an extrinsic.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>keypair</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>method</code></strong> :&ensp;<code>name</code> of <code>message to execute</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>args</code></strong> :&ensp;<code>arguments</code> of <code>message in {'name': value} format</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>value</code></strong> :&ensp;<code>value to send when executing the message</code></dt>
<dd>&nbsp;</dd>
</dl>
<p>gas_limit:</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>GenericContractExecResult</code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read(self, keypair: Keypair, method: str, args: dict = None,
         value: int = 0, gas_limit: int = 5000000000000) -&gt; GenericContractExecResult:
    &#34;&#34;&#34;
    Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used
    to predict gas limits and &#39;dry-run&#39; the execution when a mutable message is used.
    This method does not submit an extrinsic.

    Parameters
    ----------
    keypair
    method: name of message to execute
    args: arguments of message in {&#39;name&#39;: value} format
    value: value to send when executing the message
    gas_limit:

    Returns
    -------
    GenericContractExecResult
    &#34;&#34;&#34;

    input_data = self.metadata.generate_message_data(name=method, args=args)

    response = self.substrate.rpc_request(method=&#39;contracts_call&#39;, params=[{
        &#39;dest&#39;: self.contract_address,
        &#39;gasLimit&#39;: gas_limit,
        &#39;inputData&#39;: input_data.to_hex(),
        &#39;origin&#39;: keypair.ss58_address,
        &#39;value&#39;: value
    }])

    if &#39;result&#39; in response:

        return_type_string = self.metadata.get_return_type_string_for_message(method)

        # Wrap the result in a ContractExecResult Enum because the exec will result in the same
        ContractExecResult = self.substrate.runtime_config.get_decoder_class(&#39;ContractExecResult&#39;)

        contract_exec_result = ContractExecResult(contract_result_scale_type=return_type_string)

        if &#39;result&#39; in response[&#39;result&#39;]:

            contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;gasConsumed&#39;]

            if &#39;Ok&#39; in response[&#39;result&#39;][&#39;result&#39;]:

                contract_exec_result.flags = response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;flags&#39;]

                try:

                    result_scale_obj = self.substrate.decode_scale(
                        type_string=return_type_string,
                        scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;]),
                        return_scale_obj=True
                    )

                    response[&#39;result&#39;][&#39;result&#39;][&#39;Ok&#39;][&#39;data&#39;] = result_scale_obj.value
                    contract_exec_result.contract_result_data = result_scale_obj

                except NotImplementedError:
                    pass

        # Backwards compatibility
        elif &#39;success&#39; in response[&#39;result&#39;]:

            contract_exec_result.gas_consumed = response[&#39;result&#39;][&#39;success&#39;][&#39;gas_consumed&#39;]
            contract_exec_result.flags = response[&#39;result&#39;][&#39;success&#39;][&#39;flags&#39;]

            try:

                result_scale_obj = self.substrate.decode_scale(
                    type_string=return_type_string,
                    scale_bytes=ScaleBytes(response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;]),
                    return_scale_obj=True
                )

                response[&#39;result&#39;][&#39;success&#39;][&#39;data&#39;] = result_scale_obj.value
                contract_exec_result.contract_result_data = result_scale_obj

            except NotImplementedError:
                pass

        contract_exec_result.value = response[&#39;result&#39;]

        return contract_exec_result

    raise ContractReadFailedException(response)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="substrateinterface.contracts.ContractMetadata"><code class="flex name class">
<span>class <span class="ident">ContractMetadata</span></span>
<span>(</span><span>metadata_dict: dict, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a>)</span>
</code></dt>
<dd>
<div class="desc"><p>Class using the generated metadata.json file to represent the metadata of a contract. The metadata_dict is
parsed and the used types are extracted, composed and added to the type registry of the runtime</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>metadata_dict</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContractMetadata:

    def __init__(self, metadata_dict: dict, substrate: SubstrateInterface):
        &#34;&#34;&#34;
        Class using the generated metadata.json file to represent the metadata of a contract. The metadata_dict is
        parsed and the used types are extracted, composed and added to the type registry of the runtime

        Parameters
        ----------
        metadata_dict
        substrate
        &#34;&#34;&#34;
        self.metadata_dict = metadata_dict
        self.substrate = substrate
        self.type_registry = {}

        self.__type_offset = 0

        self.__parse_type_registry()

    @classmethod
    def create_from_file(cls, metadata_file: str, substrate: SubstrateInterface) -&gt; &#34;ContractMetadata&#34;:
        &#34;&#34;&#34;
        Create a new ContractMetadata object using the provided metadata_file, usually generated by the command
        &#34;cargo +nightly contract generate-metadata&#34; in an ink! project

        Parameters
        ----------
        metadata_file
        substrate

        Returns
        -------
        ContractMetadata
        &#34;&#34;&#34;
        with open(os.path.abspath(metadata_file), &#39;r&#39;) as fp:
            metadata_string = fp.read()
        return cls(json.loads(metadata_string), substrate)

    def __getattr__(self, item):
        if item in self.metadata_dict:
            return self.metadata_dict[item]
        else:
            raise AttributeError(&#34;&#39;{}&#39; object has no attribute &#39;{}&#39;&#34;.format(self.__class__.__name__, item))

    def __parse_type_registry(self):

        # Check requirements
        if &#39;types&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;No &#39;types&#39; directive present in metadata file&#34;)

        if &#39;spec&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;&#39;spec&#39; directive not present in metadata file&#34;)

        if &#39;constructors&#39; not in self.metadata_dict[&#39;spec&#39;]:
            raise ContractMetadataParseException(&#34;No constructors present in metadata file&#34;)

        if &#39;messages&#39; not in self.metadata_dict[&#39;spec&#39;]:
            raise ContractMetadataParseException(&#34;No messages present in metadata file&#34;)

        if &#39;source&#39; not in self.metadata_dict:
            raise ContractMetadataParseException(&#34;&#39;source&#39; directive not present in metadata file&#34;)

        # check Metadata version
        if version.parse(self.metadata_dict[&#39;metadataVersion&#39;]) &lt; version.parse(&#39;0.7.0&#39;):
            # Type indexes are 1-based before 0.7.0
            self.__type_offset = 1

        self.type_string_prefix = f&#34;ink.{self.metadata_dict[&#39;source&#39;][&#39;hash&#39;]}&#34;

        for idx, metadata_type in enumerate(self.metadata_dict[&#39;types&#39;]):

            idx += self.__type_offset

            if idx not in self.type_registry:
                self.type_registry[idx] = self.get_type_string_for_metadata_type(idx)

    def generate_constructor_data(self, name, args: dict = None) -&gt; ScaleBytes:
        &#34;&#34;&#34;
        Compose the data field used in the &#34;Contracts.instantiate&#34; call, finding the selectors and encoded the args
        of given constructor

        Parameters
        ----------
        name
        args

        Returns
        -------
        ScaleBytes
        &#34;&#34;&#34;
        if not args:
            args = {}

        for constructor in self.metadata_dict[&#39;spec&#39;][&#39;constructors&#39;]:
            if name in constructor[&#39;name&#39;]:
                data = ScaleBytes(constructor[&#39;selector&#39;])

                for arg in constructor[&#39;args&#39;]:
                    if arg[&#39;name&#39;] not in args:
                        raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                    else:
                        data += self.substrate.encode_scale(
                            type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                            value=args[arg[&#39;name&#39;]]
                        )
                return data

        raise ValueError(f&#39;Constructor &#34;{name}&#34; not found&#39;)

    def get_type_string_for_metadata_type(self, type_id: int) -&gt; str:
        &#34;&#34;&#34;
        Adds a type included in the metadata (represented by an index in the type list) to the type registry and
        produces a type string that can be used in the scope of the `RuntimeConfigurationObject`.

        Parameters
        ----------
        type_id 1-based index of type locating in the metadata types dict

        Returns
        -------
        str
        &#34;&#34;&#34;

        # Check if already processed
        if type_id in self.type_registry:
            return self.type_registry[type_id]

        if type_id &gt; len(self.metadata_dict[&#39;types&#39;]):
            raise ValueError(f&#39;type_id {type_id} not found in metadata&#39;)

        arg_type = self.metadata_dict[&#39;types&#39;][type_id - 1]

        if &#39;path&#39; in arg_type:

            # Option field
            if arg_type[&#39;path&#39;] == [&#39;Option&#39;]:

                # Examine the fields in the &#39;Some&#39; variant
                options_fields = arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;][1][&#39;fields&#39;]

                if len(options_fields) == 1:
                    sub_type = self.get_type_string_for_metadata_type(options_fields[0][&#39;type&#39;])
                else:
                    raise NotImplementedError(&#39;Tuples in Option field not yet supported&#39;)

                return f&#34;Option&lt;{sub_type}&gt;&#34;

            # Predefined types defined in crate ink_env
            if arg_type[&#39;path&#39;][0:2] == [&#39;ink_env&#39;, &#39;types&#39;]:

                if arg_type[&#39;path&#39;][2] == &#39;Timestamp&#39;:
                    return &#39;Moment&#39;

                elif arg_type[&#39;path&#39;][2] in [&#39;AccountId&#39;, &#39;Hash&#39;, &#39;Balance&#39;, &#39;BlockNumber&#39;]:
                    return arg_type[&#39;path&#39;][2]

                else:
                    raise NotImplementedError(f&#34;Unsupported ink_env type &#39;{arg_type[&#39;path&#39;][2]}&#39;&#34;)

        # RUST primitives
        if &#39;primitive&#39; in arg_type[&#39;def&#39;]:
            return arg_type[&#39;def&#39;][&#39;primitive&#39;]

        elif &#39;array&#39; in arg_type[&#39;def&#39;]:
            array_type = self.get_type_string_for_metadata_type(arg_type[&#39;def&#39;][&#39;array&#39;][&#39;type&#39;])
            # Generate unique type string
            return f&#34;[{array_type}; {arg_type[&#39;def&#39;][&#39;array&#39;][&#39;len&#39;]}]&#34;

        elif &#39;variant&#39; in arg_type[&#39;def&#39;]:
            # Create Enum
            type_definition = {
              &#34;type&#34;: &#34;enum&#34;,
              &#34;type_mapping&#34;: []
            }
            for variant in arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;]:

                if &#39;fields&#39; in variant:
                    if len(variant[&#39;fields&#39;]) &gt; 1:
                        raise NotImplementedError(&#39;Tuples as field of enums not supported&#39;)

                    enum_value = self.get_type_string_for_metadata_type(variant[&#39;fields&#39;][0][&#39;type&#39;])

                else:
                    enum_value = &#39;Null&#39;

                type_definition[&#39;type_mapping&#39;].append(
                    [variant[&#39;name&#39;], enum_value]
                )

            # Add to type registry
            self.substrate.runtime_config.update_type_registry_types(
                {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
            )
            # Generate unique type string
            self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

            return f&#39;{self.type_string_prefix}.{type_id}&#39;

        elif &#39;composite&#39; in arg_type[&#39;def&#39;]:
            # Create Struct
            type_definition = {
                &#34;type&#34;: &#34;struct&#34;,
                &#34;type_mapping&#34;: []
            }

            for field in arg_type[&#39;def&#39;][&#39;composite&#39;][&#39;fields&#39;]:
                type_definition[&#39;type_mapping&#39;].append(
                    [field[&#39;name&#39;], self.get_type_string_for_metadata_type(field[&#39;type&#39;])]
                )

            # Add to type registry
            self.substrate.runtime_config.update_type_registry_types(
                {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
            )

            # Generate unique type string
            self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

            return f&#39;{self.type_string_prefix}.{type_id}&#39;
        elif &#39;tuple&#39; in arg_type[&#39;def&#39;]:
            # Create tuple
            elements = [self.get_type_string_for_metadata_type(element) for element in arg_type[&#39;def&#39;][&#39;tuple&#39;]]
            return f&#34;({&#39;,&#39;.join(elements)})&#34;

        raise NotImplementedError(f&#34;Type &#39;{arg_type}&#39; not supported&#34;)

    def get_return_type_string_for_message(self, name) -&gt; str:
        for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
            if name in message[&#39;name&#39;]:
                if message[&#39;returnType&#39;] is None:
                    return &#39;Null&#39;
                else:
                    return self.get_type_string_for_metadata_type(message[&#39;returnType&#39;][&#39;type&#39;])

        raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)

    def generate_message_data(self, name, args: dict = None) -&gt; ScaleBytes:
        &#34;&#34;&#34;
        Compose the data field used in the &#34;Contracts.call&#34; call, finding the selector and encoded the args
        of provided message name

        Parameters
        ----------
        name: name of message in contract
        args: arguments required by message, in format: `{&#39;name&#39;: value}`

        Returns
        -------
        ScaleBytes
        &#34;&#34;&#34;
        if not args:
            args = {}

        for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
            if name in message[&#39;name&#39;]:
                data = ScaleBytes(message[&#39;selector&#39;])

                for arg in message[&#39;args&#39;]:
                    if arg[&#39;name&#39;] not in args:
                        raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                    else:

                        data += self.substrate.encode_scale(
                            type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                            value=args[arg[&#39;name&#39;]]
                        )
                return data

        raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)

    def get_event_data(self, event_id: int) -&gt; dict:
        &#34;&#34;&#34;
        Looks up the event data for given 0-based event_id

        Parameters
        ----------
        event_id

        Returns
        -------

        &#34;&#34;&#34;
        if event_id &gt; len(self.metadata_dict[&#39;spec&#39;][&#39;events&#39;]):
            raise ValueError(f&#39;Event ID {event_id} not found&#39;)

        return self.metadata_dict[&#39;spec&#39;][&#39;events&#39;][event_id]</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractMetadata.create_from_file"><code class="name flex">
<span>def <span class="ident">create_from_file</span></span>(<span>metadata_file: str, substrate: <a title="substrateinterface.base.SubstrateInterface" href="base.html#substrateinterface.base.SubstrateInterface">SubstrateInterface</a>) ‑> <a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a></span>
</code></dt>
<dd>
<div class="desc"><p>Create a new ContractMetadata object using the provided metadata_file, usually generated by the command
"cargo +nightly contract generate-metadata" in an ink! project</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>metadata_file</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>substrate</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a></code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@classmethod
def create_from_file(cls, metadata_file: str, substrate: SubstrateInterface) -&gt; &#34;ContractMetadata&#34;:
    &#34;&#34;&#34;
    Create a new ContractMetadata object using the provided metadata_file, usually generated by the command
    &#34;cargo +nightly contract generate-metadata&#34; in an ink! project

    Parameters
    ----------
    metadata_file
    substrate

    Returns
    -------
    ContractMetadata
    &#34;&#34;&#34;
    with open(os.path.abspath(metadata_file), &#39;r&#39;) as fp:
        metadata_string = fp.read()
    return cls(json.loads(metadata_string), substrate)</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="substrateinterface.contracts.ContractMetadata.generate_constructor_data"><code class="name flex">
<span>def <span class="ident">generate_constructor_data</span></span>(<span>self, name, args: dict = None) ‑> scalecodec.base.ScaleBytes</span>
</code></dt>
<dd>
<div class="desc"><p>Compose the data field used in the "Contracts.instantiate" call, finding the selectors and encoded the args
of given constructor</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>name</code></strong></dt>
<dd>&nbsp;</dd>
<dt><strong><code>args</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ScaleBytes</code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def generate_constructor_data(self, name, args: dict = None) -&gt; ScaleBytes:
    &#34;&#34;&#34;
    Compose the data field used in the &#34;Contracts.instantiate&#34; call, finding the selectors and encoded the args
    of given constructor

    Parameters
    ----------
    name
    args

    Returns
    -------
    ScaleBytes
    &#34;&#34;&#34;
    if not args:
        args = {}

    for constructor in self.metadata_dict[&#39;spec&#39;][&#39;constructors&#39;]:
        if name in constructor[&#39;name&#39;]:
            data = ScaleBytes(constructor[&#39;selector&#39;])

            for arg in constructor[&#39;args&#39;]:
                if arg[&#39;name&#39;] not in args:
                    raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                else:
                    data += self.substrate.encode_scale(
                        type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                        value=args[arg[&#39;name&#39;]]
                    )
            return data

    raise ValueError(f&#39;Constructor &#34;{name}&#34; not found&#39;)</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractMetadata.generate_message_data"><code class="name flex">
<span>def <span class="ident">generate_message_data</span></span>(<span>self, name, args: dict = None) ‑> scalecodec.base.ScaleBytes</span>
</code></dt>
<dd>
<div class="desc"><p>Compose the data field used in the "Contracts.call" call, finding the selector and encoded the args
of provided message name</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>name</code></strong> :&ensp;<code>name</code> of <code>message in contract</code></dt>
<dd>&nbsp;</dd>
<dt><strong><code>args</code></strong> :&ensp;<code _name_:="'name':" value>arguments required by message, in format:</code>``</dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ScaleBytes</code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def generate_message_data(self, name, args: dict = None) -&gt; ScaleBytes:
    &#34;&#34;&#34;
    Compose the data field used in the &#34;Contracts.call&#34; call, finding the selector and encoded the args
    of provided message name

    Parameters
    ----------
    name: name of message in contract
    args: arguments required by message, in format: `{&#39;name&#39;: value}`

    Returns
    -------
    ScaleBytes
    &#34;&#34;&#34;
    if not args:
        args = {}

    for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
        if name in message[&#39;name&#39;]:
            data = ScaleBytes(message[&#39;selector&#39;])

            for arg in message[&#39;args&#39;]:
                if arg[&#39;name&#39;] not in args:
                    raise ValueError(f&#34;Argument \&#34;{arg[&#39;name&#39;]}\&#34; is missing&#34;)
                else:

                    data += self.substrate.encode_scale(
                        type_string=self.get_type_string_for_metadata_type(arg[&#39;type&#39;][&#39;type&#39;]),
                        value=args[arg[&#39;name&#39;]]
                    )
            return data

    raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractMetadata.get_event_data"><code class="name flex">
<span>def <span class="ident">get_event_data</span></span>(<span>self, event_id: int) ‑> dict</span>
</code></dt>
<dd>
<div class="desc"><p>Looks up the event data for given 0-based event_id</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>event_id</code></strong></dt>
<dd>&nbsp;</dd>
</dl>
<h2 id="returns">Returns</h2></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_event_data(self, event_id: int) -&gt; dict:
    &#34;&#34;&#34;
    Looks up the event data for given 0-based event_id

    Parameters
    ----------
    event_id

    Returns
    -------

    &#34;&#34;&#34;
    if event_id &gt; len(self.metadata_dict[&#39;spec&#39;][&#39;events&#39;]):
        raise ValueError(f&#39;Event ID {event_id} not found&#39;)

    return self.metadata_dict[&#39;spec&#39;][&#39;events&#39;][event_id]</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractMetadata.get_return_type_string_for_message"><code class="name flex">
<span>def <span class="ident">get_return_type_string_for_message</span></span>(<span>self, name) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_return_type_string_for_message(self, name) -&gt; str:
    for message in self.metadata_dict[&#39;spec&#39;][&#39;messages&#39;]:
        if name in message[&#39;name&#39;]:
            if message[&#39;returnType&#39;] is None:
                return &#39;Null&#39;
            else:
                return self.get_type_string_for_metadata_type(message[&#39;returnType&#39;][&#39;type&#39;])

    raise ValueError(f&#39;Message &#34;{name}&#34; not found&#39;)</code></pre>
</details>
</dd>
<dt id="substrateinterface.contracts.ContractMetadata.get_type_string_for_metadata_type"><code class="name flex">
<span>def <span class="ident">get_type_string_for_metadata_type</span></span>(<span>self, type_id: int) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Adds a type included in the metadata (represented by an index in the type list) to the type registry and
produces a type string that can be used in the scope of the <code>RuntimeConfigurationObject</code>.</p>
<h2 id="parameters">Parameters</h2>
<p>type_id 1-based index of type locating in the metadata types dict</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>&nbsp;</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_type_string_for_metadata_type(self, type_id: int) -&gt; str:
    &#34;&#34;&#34;
    Adds a type included in the metadata (represented by an index in the type list) to the type registry and
    produces a type string that can be used in the scope of the `RuntimeConfigurationObject`.

    Parameters
    ----------
    type_id 1-based index of type locating in the metadata types dict

    Returns
    -------
    str
    &#34;&#34;&#34;

    # Check if already processed
    if type_id in self.type_registry:
        return self.type_registry[type_id]

    if type_id &gt; len(self.metadata_dict[&#39;types&#39;]):
        raise ValueError(f&#39;type_id {type_id} not found in metadata&#39;)

    arg_type = self.metadata_dict[&#39;types&#39;][type_id - 1]

    if &#39;path&#39; in arg_type:

        # Option field
        if arg_type[&#39;path&#39;] == [&#39;Option&#39;]:

            # Examine the fields in the &#39;Some&#39; variant
            options_fields = arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;][1][&#39;fields&#39;]

            if len(options_fields) == 1:
                sub_type = self.get_type_string_for_metadata_type(options_fields[0][&#39;type&#39;])
            else:
                raise NotImplementedError(&#39;Tuples in Option field not yet supported&#39;)

            return f&#34;Option&lt;{sub_type}&gt;&#34;

        # Predefined types defined in crate ink_env
        if arg_type[&#39;path&#39;][0:2] == [&#39;ink_env&#39;, &#39;types&#39;]:

            if arg_type[&#39;path&#39;][2] == &#39;Timestamp&#39;:
                return &#39;Moment&#39;

            elif arg_type[&#39;path&#39;][2] in [&#39;AccountId&#39;, &#39;Hash&#39;, &#39;Balance&#39;, &#39;BlockNumber&#39;]:
                return arg_type[&#39;path&#39;][2]

            else:
                raise NotImplementedError(f&#34;Unsupported ink_env type &#39;{arg_type[&#39;path&#39;][2]}&#39;&#34;)

    # RUST primitives
    if &#39;primitive&#39; in arg_type[&#39;def&#39;]:
        return arg_type[&#39;def&#39;][&#39;primitive&#39;]

    elif &#39;array&#39; in arg_type[&#39;def&#39;]:
        array_type = self.get_type_string_for_metadata_type(arg_type[&#39;def&#39;][&#39;array&#39;][&#39;type&#39;])
        # Generate unique type string
        return f&#34;[{array_type}; {arg_type[&#39;def&#39;][&#39;array&#39;][&#39;len&#39;]}]&#34;

    elif &#39;variant&#39; in arg_type[&#39;def&#39;]:
        # Create Enum
        type_definition = {
          &#34;type&#34;: &#34;enum&#34;,
          &#34;type_mapping&#34;: []
        }
        for variant in arg_type[&#39;def&#39;][&#39;variant&#39;][&#39;variants&#39;]:

            if &#39;fields&#39; in variant:
                if len(variant[&#39;fields&#39;]) &gt; 1:
                    raise NotImplementedError(&#39;Tuples as field of enums not supported&#39;)

                enum_value = self.get_type_string_for_metadata_type(variant[&#39;fields&#39;][0][&#39;type&#39;])

            else:
                enum_value = &#39;Null&#39;

            type_definition[&#39;type_mapping&#39;].append(
                [variant[&#39;name&#39;], enum_value]
            )

        # Add to type registry
        self.substrate.runtime_config.update_type_registry_types(
            {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
        )
        # Generate unique type string
        self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

        return f&#39;{self.type_string_prefix}.{type_id}&#39;

    elif &#39;composite&#39; in arg_type[&#39;def&#39;]:
        # Create Struct
        type_definition = {
            &#34;type&#34;: &#34;struct&#34;,
            &#34;type_mapping&#34;: []
        }

        for field in arg_type[&#39;def&#39;][&#39;composite&#39;][&#39;fields&#39;]:
            type_definition[&#39;type_mapping&#39;].append(
                [field[&#39;name&#39;], self.get_type_string_for_metadata_type(field[&#39;type&#39;])]
            )

        # Add to type registry
        self.substrate.runtime_config.update_type_registry_types(
            {f&#39;{self.type_string_prefix}.{type_id}&#39;: type_definition}
        )

        # Generate unique type string
        self.type_registry[type_id] = f&#39;{self.type_string_prefix}.{type_id}&#39;

        return f&#39;{self.type_string_prefix}.{type_id}&#39;
    elif &#39;tuple&#39; in arg_type[&#39;def&#39;]:
        # Create tuple
        elements = [self.get_type_string_for_metadata_type(element) for element in arg_type[&#39;def&#39;][&#39;tuple&#39;]]
        return f&#34;({&#39;,&#39;.join(elements)})&#34;

    raise NotImplementedError(f&#34;Type &#39;{arg_type}&#39; not supported&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="substrateinterface" href="index.html">substrateinterface</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="substrateinterface.contracts.ContractCode" href="#substrateinterface.contracts.ContractCode">ContractCode</a></code></h4>
<ul class="">
<li><code><a title="substrateinterface.contracts.ContractCode.create_from_code_hash" href="#substrateinterface.contracts.ContractCode.create_from_code_hash">create_from_code_hash</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractCode.create_from_contract_files" href="#substrateinterface.contracts.ContractCode.create_from_contract_files">create_from_contract_files</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractCode.deploy" href="#substrateinterface.contracts.ContractCode.deploy">deploy</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractCode.upload_wasm" href="#substrateinterface.contracts.ContractCode.upload_wasm">upload_wasm</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="substrateinterface.contracts.ContractEvent" href="#substrateinterface.contracts.ContractEvent">ContractEvent</a></code></h4>
<ul class="">
<li><code><a title="substrateinterface.contracts.ContractEvent.process" href="#substrateinterface.contracts.ContractEvent.process">process</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractEvent.process_encode" href="#substrateinterface.contracts.ContractEvent.process_encode">process_encode</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="substrateinterface.contracts.ContractExecutionReceipt" href="#substrateinterface.contracts.ContractExecutionReceipt">ContractExecutionReceipt</a></code></h4>
<ul class="">
<li><code><a title="substrateinterface.contracts.ContractExecutionReceipt.contract_events" href="#substrateinterface.contracts.ContractExecutionReceipt.contract_events">contract_events</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractExecutionReceipt.create_from_extrinsic_receipt" href="#substrateinterface.contracts.ContractExecutionReceipt.create_from_extrinsic_receipt">create_from_extrinsic_receipt</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractExecutionReceipt.process_events" href="#substrateinterface.contracts.ContractExecutionReceipt.process_events">process_events</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="substrateinterface.contracts.ContractInstance" href="#substrateinterface.contracts.ContractInstance">ContractInstance</a></code></h4>
<ul class="">
<li><code><a title="substrateinterface.contracts.ContractInstance.create_from_address" href="#substrateinterface.contracts.ContractInstance.create_from_address">create_from_address</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractInstance.exec" href="#substrateinterface.contracts.ContractInstance.exec">exec</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractInstance.read" href="#substrateinterface.contracts.ContractInstance.read">read</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="substrateinterface.contracts.ContractMetadata" href="#substrateinterface.contracts.ContractMetadata">ContractMetadata</a></code></h4>
<ul class="">
<li><code><a title="substrateinterface.contracts.ContractMetadata.create_from_file" href="#substrateinterface.contracts.ContractMetadata.create_from_file">create_from_file</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractMetadata.generate_constructor_data" href="#substrateinterface.contracts.ContractMetadata.generate_constructor_data">generate_constructor_data</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractMetadata.generate_message_data" href="#substrateinterface.contracts.ContractMetadata.generate_message_data">generate_message_data</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractMetadata.get_event_data" href="#substrateinterface.contracts.ContractMetadata.get_event_data">get_event_data</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractMetadata.get_return_type_string_for_message" href="#substrateinterface.contracts.ContractMetadata.get_return_type_string_for_message">get_return_type_string_for_message</a></code></li>
<li><code><a title="substrateinterface.contracts.ContractMetadata.get_type_string_for_metadata_type" href="#substrateinterface.contracts.ContractMetadata.get_type_string_for_metadata_type">get_type_string_for_metadata_type</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.1</a>.</p>
</footer>
</body>
</html>